package cn.jhh.content.service.impl;

import cn.jhh.base.enums.BizDictEnum;
import cn.jhh.base.exception.CustomException;
import cn.jhh.content.mapper.CourseMarketMapper;
import cn.jhh.content.model.dto.AddCourseDto;
import cn.jhh.content.model.dto.CourseBaseInfoDto;
import cn.jhh.content.model.dto.UpdateCourseDto;
import cn.jhh.content.model.entity.CourseBase;
import cn.jhh.content.mapper.CourseBaseMapper;
import cn.jhh.content.model.entity.CourseCategory;
import cn.jhh.content.model.entity.CourseMarket;
import cn.jhh.content.service.CourseBaseService;
import cn.jhh.content.service.CourseCategoryService;
import cn.jhh.content.service.TeachplanService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author jhh
 * @since 2025-05-23
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Resource
    private TeachplanService teachplanService;

    @Resource
    private CourseMarketMapper courseMarketMapper;
    
    @Resource
    private CourseCategoryService courseCategoryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
        //向Course_base课程基本信息表表添加数据
        CourseBase courseBase = new CourseBase();
        //以上设置数据的方法可以拷贝,从源拷贝到目标
        BeanUtils.copyProperties(dto, courseBase);
        //设置机构id
        courseBase.setCompanyId(companyId);
        //创建时间
        courseBase.setCreateDate(LocalDateTime.now());
        //审核状态默认未提交
        courseBase.setAuditStatus("202002");
        //发布状态默认为未发布
        courseBase.setStatus("203001");

        //插入成功返回true
        boolean isSave = save(courseBase);
        if (!isSave) {
            throw CustomException.init("创建课程基本信息失败");
        }
//        得到课程Id
        //得到课程id
        Long courseId = courseBase.getId();

        //向数据库插入课程基本信息表，拿到课程的id
        //向课程营销表添加数据
        CourseMarket courseMarket = new CourseMarket();
        //两个对象的属性名一致，类型一样
        BeanUtils.copyProperties(dto, courseMarket);
        courseMarket.setId(courseId);
        int insert = saveCourseMarket(courseMarket);
        if (insert < 1) {
            throw CustomException.init("创建课程营销信息失败");
        }
//        这里是组合两个返回一个特定的数据 但是为什么这里要返回特定的值呢？
        return getCourseBaseInfo(courseId);
    }


    private int saveCourseMarket(CourseMarket courseMarket) {
        String charge = courseMarket.getCharge();
        if (StringUtils.isBlank(charge)) {
            throw CustomException.init("收费规则没有选择");
        }
        if ("201001".equals(charge)) {
            if (courseMarket.getPrice() == null || courseMarket.getPrice().floatValue() <= 0) {
                throw CustomException.init("课程为收费价格不能为空且必须大于0");
            }
        }
        return !Objects.isNull(courseMarketMapper.selectById(courseMarket.getId())) ? courseMarketMapper.updateById(courseMarket) : courseMarketMapper.insert(courseMarket);

    }


    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        //课程基本信息
        CourseBase courseBase = Optional.ofNullable(getById(courseId)).orElseThrow(() -> CustomException.init("不存在该记录"));
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //组成要返回的数据
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        //将分类的名称查询出来
        //一级分类
        CourseCategory courseCategory = courseCategoryService.getById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategory.getName());
        //二级分类
        CourseCategory courseCategory2 = courseCategoryService.getById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategory2.getName());
        return courseBaseInfoDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateCourseBaseInfo(UpdateCourseDto dto) {
//        先检查Id是否存在
        Map<String, Object> result = new HashMap<>();
        CourseBase courseBase = getById(dto.getId());
        if(courseBase == null)
        {
            throw CustomException.init("课程不存在");
        }
//        更新课程基本信息
        BeanUtils.copyProperties(dto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        boolean updateResult = updateById(courseBase);
        if(!updateResult){
            throw CustomException.init("更新课程基本信息失败");
        }
//      把其余信息给营销表
        CourseMarket courseMarket = new CourseMarket();
        Long courseId = courseBase.getId();
        BeanUtils.copyProperties(dto,courseMarket);
        courseMarket.setId(courseId);
        int marketResult = saveCourseMarket(courseMarket);
        if(marketResult <= 0){
            throw CustomException.init("更新课程营销信息失败");
        }
//      查询课程信息并返回结果
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        result.put("success", true);
        result.put("message", "课程信息更新成功");
        result.put("data", courseBaseInfo);

        return result;
        }

    @Override
    public void updateAuditStatusToC202002(Long companyId, Long courseId) {
//        这里需要写方法去校验是否能编辑
        checkCourseIsEdit(companyId, courseId);
        update(new LambdaUpdateWrapper<CourseBase>().eq(CourseBase::getId,courseId)
                .set(CourseBase::getAuditStatus,BizDictEnum.C202_2.getCode()));
    }

    private CourseBase checkCourseIsEdit(Long companyId, Long courseId) {
        CourseBase courseBase = getById(courseId);
        if(courseBase == null)
        {
            throw CustomException.init("当前课程不存在");
        }
//      校验本机构只能修改本机构的课程
        if(!companyId.equals(courseBase.getCompanyId())){
            throw CustomException.init("只能操作当前机构的课程");
        }
//        已经提交的不能编辑
        if (BizDictEnum.C202_3.getCode().equals(courseBase.getAuditStatus())) {
            throw CustomException.init("请先等待课程审核后在操作");
        }
//          已上架的不可编辑
        if(BizDictEnum.C203_2.getCode().equals(courseBase.getAuditStatus())){
            throw CustomException.init("请先下架课程后在操作");
        }
        return courseBase;
    }
}
